package com.hzchendou.blog.demo.gateway.security.handler;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.hzchendou.blog.demo.common.model.vo.ResultVO;
import java.nio.charset.StandardCharsets;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.server.authorization.ServerAccessDeniedHandler;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.netty.ByteBufFlux;

/**
 * @Date: 2022-05-13 15:47
 * @since: 1.0
 */
@Slf4j
@Component
public class AccessDeniedHandler implements ServerAccessDeniedHandler {

    @Override
    public Mono<Void> handle(ServerWebExchange serverWebExchange, AccessDeniedException e) {
        ResultVO<String> resultVO = ResultVO.fail("无权限访问");
        ServerHttpResponse response = serverWebExchange.getResponse();
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        Mono<Void> ret = null;
        try {
            ret = response.writeAndFlushWith(
                    Flux.just(ByteBufFlux
                            .just(response.bufferFactory().wrap(resultVO.toJson().getBytes(
                                    StandardCharsets.UTF_8)))));
        } catch (JsonProcessingException ex) {
            log.error("无权限访问处理异常", ex);
        }
        return ret;
    }
}
